//
//  LRXSeacheThingControllerViewController.m
//  路人侠
//
//  Created by zhangxulong on 5/15/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXSeacheThingController.h"
#import "LRXSearchThingTableViewCell.h"
#import "LRXThing.h"
#import "LRXThingRemaindView.h"
#import "AppDelegate.h"
#import "LRXBuyThingCell.h"
#import "LRXBuyStoreModel.h"
#import "LRXBuyThingController.h"
#import "LRXSubThingView.h"
#import "LRXLMeController.h"
@interface LRXSeacheThingController () <UITableViewDelegate,UITableViewDataSource,LRXThingRemaindViewDelegate,UITextViewDelegate>
@property(nonatomic,strong) UITextField * searchText;
@property(nonatomic,strong)UILabel * countLabel;
@property(nonatomic,assign)NSInteger * count;
@property(nonatomic,strong)NSMutableArray * thingS;
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,assign)BOOL isSearch;
@property(nonatomic,strong)NSMutableArray * buyThing;
@property(nonatomic,weak)LRXThingRemaindView * thingRemind;
@property(nonatomic,weak)NSArray * buyThings;
@end

@implementation LRXSeacheThingController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    
    _count=0;
    _isSearch=false;
    //_model = [[LRXSearchThingModel alloc]init];
    _buyThing = [[NSMutableArray alloc] init];
    
   
    
     UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
         //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
         tapGestureRecognizer.cancelsTouchesInView = NO;
         //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UITextField * search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, MainScreenW - 60 * wScale, NavbarH * 0.6)];
    self.searchText = search;
    search.placeholder = @"请输入商品名";
    search.font = [UIFont systemFontOfSize:20 * hScale];
    search.backgroundColor = [UIColor whiteColor];
    search.layer.cornerRadius = 5 * hScale;
    UIImageView * image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"searchImage"]];
    image.frame = CGRectMake(0, 0, 20 * hScale, 20 * hScale);
    search.leftView = image;
    search.leftViewMode = UITextFieldViewModeAlways;
    
    self.navigationItem.titleView = search;
    UIButton * searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:20 * hScale];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchBtn];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainScreenW, MainScreenH - NavbarH - statuesH-100*hScale) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.searchText becomeFirstResponder];
    
    [self remained];
    
}
-(void)remained{
    
    LRXThingRemaindView * thingRemind = [[LRXThingRemaindView alloc]init];
    thingRemind.alpha = 0.7;
    thingRemind.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100 * wScale);
    thingRemind.thingRemaindDelegate = self;
    [thingRemind thingRemaindView];
    

    self.thingRemind = thingRemind;
    
    
    [self.view addSubview:self.thingRemind];
    
    
}
- (void)searchBtnClick
{
    if (self.searchText.text.length <= 0) {
        [MBProgressHUD showError:@"请输入商品名"];
    }
    else
    {
        [MBProgressHUD showMessage:@"加载中..." toView:[UIApplication sharedApplication].keyWindow];
        _thingS = [[NSMutableArray alloc] init];
        NSDictionary * param = @{@"s":@"2",@"key":@"炒饭"}; //请求学校购买地点
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        manger.requestSerializer.timeoutInterval = 2;
        [manger GET:searchUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
            
        
            
            NSInteger  stateCode = [responseObject[@"data"][@"status_code"] integerValue];
            
            if (!(_thingS==NULL)) {
                [_thingS removeAllObjects];
            }
            if (stateCode == 1) {
                for (NSDictionary * dic in responseObject[@"data"][@"dataset"]) {
                    
                    LRXThing * searchModel = [LRXThing thingWith:dic];
                    [_thingS addObject:searchModel];
                    [self.view addSubview:_tableView];
            }
                
                _isSearch=true;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [_tableView reloadData];
                    
                });
                
           }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow];
            [MBProgressHUD showError:@"网络错误"];
        }];
    }
    
    [self.searchText resignFirstResponder];
    
}
#pragma mark -UITableView的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isSearch) {
        
        static NSString * thingReUsedCell = @"thingReUsedCell";
        LRXSearchThingTableViewCell * foodCell = [tableView dequeueReusableCellWithIdentifier:thingReUsedCell];
        if (foodCell == nil) {
            foodCell = [[LRXSearchThingTableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:thingReUsedCell];
            
            foodCell.thingInfo = self.thingS[indexPath.row];
            LRXThing * thing = [[LRXThing alloc] init];
            thing = self.thingS[indexPath.row];
            NSLog(@"myself:%@",thing.thingId);
            [foodCell layoutSearchBuyThingCellSubView];
            
        }
        else
        {
            foodCell.thingInfo = self.thingS[indexPath.row];
            [foodCell setSarchBuyThingCellModel];
        }
        [foodCell setDelegate:self];
        foodCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return foodCell;
        
    }
    else{
    
     return nil;
    
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!_isSearch) {
        return 0;
    }
    return _thingS.count;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 195 * hScale;
}
#pragma mark - accpetBtnClick  UIButton
- (void)accpetBtnClick
{
    
    if ([LRXLMeController getSaveThingOfZero]!=nil) {
        
        [[LRXLMeController getSaveThingOfZero] removeAllObjects];
        
    }
    for (LRXThing *thing in [LRXBuyThingCell getBuyThing]) {
        
        thing.reChonoseAddCount = 0;
        thing.reChonoseSubCount = 0;
    }
    
   
    _buyThings = [NSArray arrayWithArray:(NSArray *)[LRXBuyThingCell getSelectedArray]];
    
    [LRXBuyThingCell setBuyThing:_buyThings];
    NSLog(@"%@",[LRXBuyThingCell getBuyThing]);
    
    if ([self.buyThingDelegate respondsToSelector:@selector(popThingView:)]) {
        [self.buyThingDelegate popThingView:[LRXBuyThingCell getBuyThing]];
    }
    
    //推出控制器
    [self popViewController];
}
- (void)popViewController
{
    [LRXLMeController setBuy:[LRXBuyThingCell getSelectedArray]];
    LRXLMeController *viewCtl = self.navigationController.viewControllers[1];
    [self.navigationController popToViewController:viewCtl animated:YES];
    
}
- (void)updateSearchThingRemind:(NSMutableArray *)thingArray
{
    NSInteger sumThingCount = 0;
    CGFloat sumThingMoney = 0;
    for (LRXThing * thing in thingArray) {
        sumThingCount += [thing.thingCount integerValue];
        sumThingMoney += ([thing.thingCount integerValue] * [thing.thingMoney floatValue]);
    }
    self.thingRemind.thingRemindMoney.text = [NSString stringWithFormat:@"共%.2lf元",sumThingMoney];
    self.thingRemind.thingRemindLabel.text = [NSString stringWithFormat:@"%ld",(long)sumThingCount];
}

- (void)showSearchThingRemind
{
    [UIView animateWithDuration:0.2 animations:^{
        self.thingRemind.frame = CGRectMake(0, self.view.frame.size.height-100*hScale, self.view.frame.size.width, 100 * hScale);
    }];
}

- (void)hideSearchThingRemind
{
    [UIView animateWithDuration:0.2 animations:^{
        self.thingRemind.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100 * hScale);
    }];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
 
    [_searchText resignFirstResponder];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self updateSearchThingRemind:[LRXBuyThingCell getSelectedArray]];
}

-(void)viewDidAppear:(BOOL)animated{
    [self showSearchThingRemind];
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [self hideSearchThingRemind];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reLoadData" object:nil];
    [LRXBuyThingController setReLoadDataBool:true];
    
}


@end
